package com.apollo.test;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.InitializingBean;

import java.util.List;

public class NacosDataSourceListener implements InitializingBean {

    public static final String GROUP_ID = "SENTINEL_GROUP";
    private static final String FLOW_RULE_TYPE = "flow";

    public static final String FLOW_DATA_ID_POSTFIX = "-" + FLOW_RULE_TYPE + "-rules";

    private String applicationName;

    private String url;

    public NacosDataSourceListener(String applicationName, String url) {
        this.applicationName = applicationName;
        this.url = url;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initDegradeRules();
    }

    private void initDegradeRules() {
        ReadableDataSource<String, List<DegradeRule>> degradeRuleDataSource = new NacosDataSource<>(
                url, GROUP_ID, applicationName + FLOW_DATA_ID_POSTFIX,
                source -> JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {
                }));
        DegradeRuleManager.register2Property(degradeRuleDataSource.getProperty());
    }
}
